package application.view
{
	import application.ApplicationFacade;
	
	import mx.containers.Box;
	import mx.controls.Alert;
	import mx.core.IFlexDisplayObject;
	import mx.managers.CursorManager;
	import mx.managers.PopUpManager;
	
	import org.puremvc.interfaces.IMediator;
	import org.puremvc.interfaces.INotification;
	import org.puremvc.patterns.mediator.Mediator;
	
	public class ApplicationMediator extends Mediator implements IMediator
	{
		public static const NAME:String = "ApplicationMediator";
		
		private var modal:IFlexDisplayObject;
		
		public function ApplicationMediator( viewComponent:Object )
		{
			super( viewComponent );
		}
		
		override public function getMediatorName():String
		{
			return NAME;
		}
		
		override public function listNotificationInterests():Array
		{
			return new Array( ApplicationFacade.SERVER_REQUEST, 
							  ApplicationFacade.SERVER_RESULT, 
							  ApplicationFacade.SERVER_FAULT,
							  ApplicationFacade.MODEL_INIT,
							  ApplicationFacade.VIEW_INIT );
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch ( notification.getName() )
			{
				case ApplicationFacade.SERVER_REQUEST:
					goModal();
					break;
					
				case ApplicationFacade.SERVER_RESULT:
					removeModal();
					break;
				
				case ApplicationFacade.SERVER_FAULT:
					removeModal();
					Alert.show( notification.getBody() as String, "Network Error" );
					break;
				
				case ApplicationFacade.MODEL_INIT:
					sendNotification( ApplicationFacade.VIEW_SETUP, main );
					break;
				
				case ApplicationFacade.VIEW_INIT:
					main.visible = true;
					break;
			}
		}
		
		protected function get main():Main
		{
			return viewComponent as Main;
		}
		
		private function goModal():void
		{
			CursorManager.setBusyCursor();
			modal = PopUpManager.createPopUp(main, Box, true);
		}
		
		private function removeModal():void
		{
			CursorManager.removeBusyCursor();
			PopUpManager.removePopUp(modal);
		}
	}
}